// pages/info/info.js

import {
  $init,
  $digest
} from '../../utils/common.js'
let http = require('../../utils/fetch.js')
var api = require('../../utils/api.js')

var app = getApp(); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: 0,
    images: [],
    imagesRoom: [],
    order_id: '',
    value: true,
    img: '',//64位图片格式
    imageUrl: "",

    identity: ["业主","家属","租客"],
    type:'',
    userName:'',
    cardType: ["身份证号","港澳台居住证","护照","其他"],
    cardTypeSelect:'身份证号',
    idCard:'',
    isSuccess: true,
    baseInfo:{},
    imagePathId:'0000'
  },
  bindPickerChange: function(e) {
    if(this.data.userName == '' || this.data.images.length == 0){
      this.setData({
        isSuccess: true,
        type: this.data.identity[e.detail.value]
      })
    } else {
      this.setData({
        isSuccess: false,
        type: this.data.identity[e.detail.value]
      })
    }
  },
  getUserName: function(e) {
    if(e.detail.value == "" || this.data.type =="" || this.data.images.length == 0) {
      this.setData({
        isSuccess: true,
        userName: e.detail.value
      })
    } else {
      this.setData({
        isSuccess: false,
        userName: e.detail.value
      })
    }
  },
  cardTypeChange: function(e) {
    this.setData({
      cardTypeSelect: this.data.cardType[e.detail.value]
    })
  },
  getIdNum: function(e) {
    this.setData({
      idCard: e.detail.value
    })
  },

  //详情里面的图片显示
  getImageUrl: function() {
    let personinfo = wx.getStorageSync('personinfo') || []
    let id = personinfo[0]._id
    let mydata = {
      CID : '510100-001',
      _id:id
    }
    http.post(api.picHeader, mydata).then((res) => {
        if (res.code == 0) {
         
          wx.showToast({
            title: "图片信息",
            icon: "none"
          })

        }

      })
      .catch((errMsg) => {
        //错误提示信息
        wx.showToast({
          title: errMsg,
          icon: "none"
        })
      });
  },
  handleValidate(){
    wx.showToast({
      title: '请先核验照片',
      icon: 'loading',
      duration: 2000
    })
  },
  //选择图片
  chooseImage(e) {
    
    let that = this
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
       
        const images = that.data.images.concat(res.tempFilePaths)
       
        that.urlTobase64(res.tempFilePaths[0])
        
        // 限制最多只能留下3张照片
        that.data.images = images.length <= 1 ? images : images.slice(0, 5)
        $digest(that)
        that.setData({
          img:that.data.images
        })
        console.log(that.data.img,"图片")
      }
    })
  },
  //转化为64位
  urlTobase64(url) {
    console.log(url,"llllll")
    wx.request({
      url: url,
      responseType: 'arraybuffer', //最关键的参数，设置返回的数据格式为arraybuffer
      success: res => {
        console.log(res,"llllll")
        //把arraybuffer转成base64
        let base64 = wx.arrayBufferToBase64(res.data);
        
        //不加上这串字符，在页面无法显示的哦
        base64　 = 'data:image/jpeg;base64,' + base64

        //打印出base64字符串，可复制到网页校验一下是否是你选择的原图片呢
        console.log(base64)
        this.setData({
          img: base64
        })
        
      },
      fail(err){
        console.log(err,'errrrrrrrrrrrrrrrr')
      }
    })
  },
//删除图片
  removeImage: function(e) {
    var that = this;
    const idx = e.target.dataset.idx
    this.data.images.splice(idx, 1)
    $digest(that)
    that.setData({
      isSuccess: true,
      images:that.data.images
    })
  },
  //图片验证
  checkPhoto() {
    //.replace(/^data:image\/\w+;base64,/,  '');
    let that=this
    const image = that.data.images
   var urls='https://smartcity.honghengxinxi.com/uploadfile'
    const arr = that.data.images.map(path => {
      return wx.uploadFile({
        url: urls, //仅为示例，非真实的接口地址
        filePath: path,
        name: 'img',
        header: {
          'content-type': 'multipart/form-data'
        },
        // formData: {
        //   image: 'image'
        // },
        success(res) {
       
         let obj=  JSON.parse(res.data);
         
          let id=(obj.id)
          console.log(that.data.imagePathId,"aa")
          console.log(id,"0000")
          
          that.setData({
              imagePathId:   id,
            })
          
          
            that.setData({
              isSuccess: false,
          
            })
                  
          // const data = res.data
          //do something
        }
      })
    })
  
    // 上传
    // 开始并行上传图片
    Promise.all(arr).then(res => {
      // 上传成功，获取这些图片在服务器上的地址，组成一个数组
      
      return res.map(item => JSON.parse(item.data).url)
    }).catch(err => {
      console.log(">>>> upload images error:", err)
    }).then(urls => {
      
    }).then(res => {
      wx.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 2000
      })
   
    }).catch(err => {
      console.log(">>>> create question error:", err)
    }).then(() => {
      // wx.hideLoading()
    })
  },
  //新增的提交
  submit:function(){
    let image = this.data.img.replace(/^data:image\/\w+;base64,/, '');
    let personinfo = wx.getStorageSync('personinfo') || []
    console.log(image, "44444")

  },
  submitData(){
  //此处为使用封装的post请求
  let myData=Object.assign(this.data.baseInfo)
  let dataObj=JSON.parse(myData)
  console.log(dataObj,'ddddddddddd')
  let params={
    name:this.data.userName,
    idCard:this.data.idCard,
    phone:this.data.phone,
    type:'029f992a-d6e4-4421-baeb-88c9d2a15f3f',
    photo:this.data.imagePathId, 
    CID:dataObj.cid,
    houser: {
    BID: dataObj.bid,
    FID: dataObj.fid,
    HID: dataObj.hid,
    UID: dataObj.uid,
   
  },
  openid:app.globalData.weixin.openid,
  xzyt:2,
  wxid:app.globalData.weixin.openid,
  weixin:app.globalData.weixin
   }

  
  http.post(api.submitData,params ).then((res) => {
    // console.log(res, 'eeee')
    
    if (res.code == 0) {
      wx.showToast({
        title: "注册成功，请耐心等待审核,即将跳转...",
        icon: "none",
        duration: 3000
      })
      setTimeout(function()
      {
        // wx.navigateTo({
        //   url:'../../pages/login/authorize/authorize'
        // })
        wx.reLaunch({
          url:'../../pages/index/index'
        })
    },3000);

     
      
    }
  })
  .catch((errMsg) => {    
    //错误提示信息
    wx.showToast({
      title: errMsg,
      icon: "none"
    })
  });
  },
  handle: function() {
    let image = this.data.img.replace(/^data:image\/\w+;base64,/, '');
    console.log(this.data.type,this.data.userName,this.data.cardTypeSelect,this.data.idCard,image)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    $init(this)
    console.log(options.data)
    this.setData({
      baseInfo:options.data
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})